package cc.linker.steplink.crm.merchant.controller.acs;

import cc.linker.steplink.crm.commons.BeanMapUtils;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.service.CommonsService;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchant.pojo.PromoterAccountPo;
import cc.linker.steplink.crm.merchant.pojo.PromoterPersonalAccountPo;
import cc.linker.steplink.crm.merchant.service.acs.PromoterAccountService;
import cc.linker.steplink.crm.response.GlobalException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 联盟商家-推广员账单
 */
@RestController
@RequestMapping("/promoter")
public class PromoterAccountController {

    @Autowired
    private PromoterAccountService pAccountService;
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    private CommonsService commonsService;
    @Autowired
    private UserInfoUtil userInfoUtil;
    /**
     * 这一步展示推广员信息
     */
    @RequestMapping("/displaypromoter")
    public Object displayPromoter(@RequestParam(value = "currentPage", defaultValue = "1", required = false) int currentPage,
                                  @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                                  @RequestBody Map<String, Object> searchMap,
                                  HttpServletRequest request) {
        //条件查询中信息可能会有推广员名称，推广员手机号，（联盟商家名称，联盟商家手机号）
        //分页信息展示，会有条件参数“currentPage”
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Integer payMode = userinfo.getPayMode();
        if (null != searchMap) {
            if (null != searchMap.get("currentPage") && !"".equals(searchMap.get("currentPage"))) {
                currentPage = (int) searchMap.get("currentPage");
            }
            if (null != searchMap.get("pageSize") && !"".equals(searchMap.get("pageSize"))) {
                pageSize = (int) searchMap.get("pageSize");
            }
        }
        PageHelper.startPage(currentPage, pageSize);
        searchMap.put("orgId", orgId);
        searchMap.put("payType", payMode + 1);
        List<PromoterAccountPo> promoterList = pAccountService.findPromoterList(searchMap);
//        assert promoterList != null;
        for (PromoterAccountPo stringMap : promoterList) {
            //  如果用户名称为空则显示用户名称为手机号4位
            if(StringUtils.isEmpty(stringMap.getCustomerName())){
                if(!StringUtils.isEmpty(stringMap.getCustomerPhone())){
                    String customerPhone = stringMap.getCustomerPhone();
                    stringMap.setCustomerName("手机尾号"+customerPhone.substring(customerPhone.length()-4)+"用户");
                }
            }
            //这里是提现总结计算
            if (null != stringMap.getSum() && !"".equals(stringMap.getSum())) {
                Long operateMoney = Long.valueOf(stringMap.getSum().toString());
                BigDecimal bigDecimal = new BigDecimal(operateMoney / 100.0).setScale(2, BigDecimal.ROUND_HALF_UP);
                stringMap.setSum(bigDecimal);
            } else {
                stringMap.setSum(0);
            }
            //这里是收入总金额计算
            if (null != stringMap.getAllMoney() && !"".equals(stringMap.getAllMoney())) {
                Long allmoney = Long.valueOf(stringMap.getAllMoney().toString());
                BigDecimal bigDecimalMoney = new BigDecimal(allmoney / 100.0).setScale(2, BigDecimal.ROUND_HALF_UP);
                stringMap.setAllMoney(bigDecimalMoney);
            } else {
                stringMap.setAllMoney(0);
            }
            // 累计代理销售业绩
            Long amount = pAccountService.getAmount(stringMap.getCustomerID(),null,null);
            BigDecimal bigDecimalAmount = new BigDecimal(amount / 100.0).setScale(2, BigDecimal.ROUND_HALF_UP);
            stringMap.setAmount(bigDecimalAmount);
        }

        return new PageInfo<>(promoterList);
    }

    /**
     * 这里记录对推广员的记账操作
     *
     * @param param
     * @param session
     * @throws GlobalException
     * @throws ParseException
     */
    @RequestMapping("/keepaccount")
    public void keepAccount(@RequestBody Map<String, Object> param, HttpServletRequest request) throws GlobalException, ParseException {
        if (StringUtils.isEmpty((String) param.get("model"))) {
            throw GlobalException.build("请选择记账模式");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String customerId = (String) param.get("customerId");
        Integer payMode = userinfo.getPayMode();

        String account = param.get("account").toString();
        if (null != account && !"".equals(account)) {
            double v = Double.parseDouble(account) * 100;
            int cent = (int) v;
            //这里金额必须大于0
            if (cent > 0) {
                //该用户提现总金额
                Integer bookeep = pAccountService.findBookeep(customerId);
                Integer amount = pAccountService.findBusiAmount(customerId);
                Map<Object, Object> map = new HashMap<>();
                if ("0".equals(param.get("model"))) {
                    //查询该用户已提现总金额
                    //int returnAmount = pAccountService.findReturnAmount(customerId);
                    if (cent <= bookeep) {
                        map.put("operateMoney", cent * -1);
                    } else {
                        throw GlobalException.build("超过用户已提现金额");
                    }
                } else {
                    //提现操作
                    //判断提现金额是否大于该用户的总收入金额
                    if (cent <= amount - bookeep) {
                        map.put("operateMoney", cent);
                    } else {
                        throw GlobalException.build("您输入的提现金额大于可提现的金额");
                    }
                }
                String adminId = userinfo.getAdminId();
                String adminName = pAccountService.findAdminName(adminId);
                Date date = new Date();
                map.put("operateTime", date);
                map.put("operator", adminName);
                map.put("customerId", customerId);
                map.put("customerName", param.get("customerName"));
                map.put("operateType", param.get("model"));
                pAccountService.updateAccount(map);
            } else {
                throw GlobalException.build("请输入大于零的金额");
            }
        } else {
            throw GlobalException.build("请输入金额");
        }
    }


    /**
     * 展示推广员个人历史账单
     *
     * @param currentPage
     * @param pageSize
     * @param searchMap
     * @return
     */
    @RequestMapping("/displayaccount")
    public Object displayAccount(@RequestParam(value = "currentPage", defaultValue = "1", required = false) int currentPage,
                                 @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                                 @RequestBody Map searchMap
    ) {
        String customerId = (String) searchMap.get("customerId");
        if (null != searchMap.get("currentPage") && !"".equals(searchMap.get("currentPage"))) {
            currentPage = (int) searchMap.get("currentPage");
        }
        if (null != searchMap.get("pageSize") && !"".equals(searchMap.get("pageSize"))) {
            pageSize = (int) searchMap.get("pageSize");
        }
        PageHelper.startPage(currentPage, pageSize);
        List<PromoterPersonalAccountPo> promoterAccount = null;
        if (!StringUtils.isEmpty(customerId)) {
            promoterAccount = pAccountService.findPromoterAccount(customerId);
            if (promoterAccount != null && promoterAccount.size() > 0) {
                for (PromoterPersonalAccountPo stringObjectMap : promoterAccount) {
                    if (stringObjectMap == null) {
                        continue;
                    }
                    Long operateMoney = (Long) stringObjectMap.getOperateMoney();
                    if (operateMoney < 0) {
                        operateMoney = operateMoney * -1;
                    }
                    BigDecimal bigDecimal = new BigDecimal(operateMoney / 100.0).setScale(2, BigDecimal.ROUND_HALF_UP);
                    stringObjectMap.setOperateMoney(bigDecimal);
                }
            }
        }
//        assert promoterAccount != null;
        return new PageInfo<>(promoterAccount);
    }

    @RequestMapping("/exportexcel")
    public void exportAccountExcel(
            @RequestParam(required = false) String leftBox,
            @RequestParam(required = false) String rightBox,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            HttpServletRequest request, HttpServletResponse response
    ) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Integer payMode = userinfo.getPayMode();
        String orgId = userinfo.getOrgId();
        endTime = org.springframework.util.StringUtils.isEmpty(endTime)? new SimpleDateFormat("yyyy-MM-dd").format(new Date()) :endTime;
        if(org.springframework.util.StringUtils.isEmpty(startTime)){
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.DATE, -30);
            Date d = c.getTime();
            startTime = new SimpleDateFormat("yyyy-MM-dd").format(d);
        }

        Map<String, Object> searchMap = new HashMap<>();
        if (null != leftBox && !"".equals(leftBox)) {
            searchMap.put("leftBox", leftBox);
        }
        if (null != rightBox && !"".equals(rightBox)) {
            searchMap.put("rightBox", rightBox);
        }
        searchMap.put("orgId", orgId);
        searchMap.put("payType", payMode + 1);
        List<PromoterAccountPo> displayPromoter = pAccountService.findPromoterList(searchMap);
//        if (1 == payMode) {
//            displayPromoter = pAccountService.findPromoterList(searchMap);
//        } else {
//            displayPromoter = pAccountService.findPromoterBusiList(searchMap);
//        }
        List<Map<String,Object>> list = new ArrayList<>();
        for (PromoterAccountPo stringMap : displayPromoter) {
            //这里是提现总结计算
            if (null != stringMap.getSum() && !"".equals(stringMap.getSum())) {
                Long operateMoney = Long.valueOf(stringMap.getSum().toString());
                BigDecimal bigDecimal = new BigDecimal(operateMoney / 100.0).setScale(2, BigDecimal.ROUND_HALF_UP);
                stringMap.setSum(bigDecimal);
            } else {
                stringMap.setSum(0);
            }
            //这里是收入总金额计算
            if (null != stringMap.getAllMoney() && !"".equals(stringMap.getAllMoney())) {
                Long allmoney = Long.valueOf(stringMap.getAllMoney().toString());
                BigDecimal bigDecimalMoney = new BigDecimal(allmoney / 100.0).setScale(2, BigDecimal.ROUND_HALF_UP);
                stringMap.setAllMoney(bigDecimalMoney);
            } else {
                stringMap.setAllMoney(0);
            }
            // 累计代理销售业绩
            Long amount = pAccountService.getAmount(stringMap.getCustomerID(),null,null);
            BigDecimal bigDecimalAmount = new BigDecimal(amount / 100.0).setScale(2, BigDecimal.ROUND_HALF_UP);
            stringMap.setAmount(bigDecimalAmount);

            // 区间代理销售业绩
            Long timeAmount = pAccountService.getAmount(stringMap.getCustomerID(),startTime,endTime);
            BigDecimal bigDecimalTimeAmount = new BigDecimal(timeAmount / 100.0).setScale(2, BigDecimal.ROUND_HALF_UP);
            stringMap.setTimeAmount(bigDecimalTimeAmount);
            //
            list.add(BeanMapUtils.beanToMap(stringMap));
        }

        String[] title = {
                "推广员名称", "推广员手机号", "所属联盟商家", "联盟商家手机号", "发展代理(个)",
                "累计收入（元）","累计已提现(元)","累计代理销售业绩(元)","区间代理销售业绩(元)"};
        String fileName = startTime+"-"+endTime+"推广员账单列表";
        String[] strings = {"customerName", "customerPhone", "pname", "pphone", "num",
                "allMoney","sum","amount","timeAmount"};
        commonsService.excelDownload(list, strings, title, fileName, response);
    }


    /**
     * 推广员邀请的加盟代理
     *
     * @param customerId
     * @return
     */
    @GetMapping("agentlist")
    public PageInfo agentList(
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
            String customerId) {
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(pAccountService.agentList(customerId));
    }

}
